package com.factory.manager.config;

import com.factory.common.constant.ResultCode;
import com.factory.common.core.LoginException;
import com.factory.common.utils.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.factory.manager.constant.ManagerConstant.*;

/**
 * 登录拦截器
 * 判断用户是否登录
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String adminToken = request.getHeader(MANAGERTOKEN);
        if(StringUtil.isEmpty(adminToken)){
            throw new LoginException(ResultCode.NoLogin.code, ResultCode.NoLogin.message);
        }
        Object attribute = request.getSession().getAttribute(getToken(adminToken));
        if(null == attribute){
            throw new LoginException(ResultCode.LoginExpired.code , ResultCode.LoginExpired.message);
        }
        return true;
    }

}